package com.ginage.gaugemanager.controller;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.ginage.gaugemanager.mapper.entity.User;
import com.ginage.gaugemanager.service.api.ILoginService;
import com.ginage.gaugemanager.utils.MD5;


@Controller
public class LoginController {
	@Autowired
	ILoginService service;
	
	@RequestMapping("login.html")
	public String loginHtml() {
		return "login.html";
	}
	@RequestMapping("login.do")
	
	public void login(User user,HttpServletRequest request,HttpServletResponse response) {
		boolean rememberme=Boolean.parseBoolean(request.getParameter("rememberme"));
		JSONObject jb = service.checkUser(user);
		HttpSession session=request.getSession();
		if(jb.get("status")=="success") {
			User currentUser = (User) jb.get("currentUser");
			session.setAttribute("currentUser", currentUser);
			session.setAttribute("currentUserName", currentUser.getUsername());
			session.setAttribute("touxiangPath",currentUser.getTouxiangPath()==null?"images/touxiang1.png":currentUser.getTouxiangPath());
			
		}
		/*
		 * if(jb.get("name")==null) { session.setAttribute("currentUserName",
		 * user.getUsername()); }else { session.setAttribute("currentUserName",
		 * jb.get("name")); } session.setAttribute("touxiangPath",
		 * jb.get("touxiangPath"));
		 */
		if(jb.get("status")=="success" && rememberme) {
			Cookie cookieUsername=new Cookie("username",user.getUsername());
			Cookie cookiePassword=new Cookie("password",MD5.parse(user.getPassword()));
			cookieUsername.setMaxAge(60*60*24*7);
			cookiePassword.setMaxAge(60*60*24*7);
			response.addCookie(cookieUsername);
			response.addCookie(cookiePassword);
		}
		try {
			response.getWriter().print(jb);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("logout.html")
	
	public String logout(HttpServletRequest request,HttpServletResponse response) {
		HttpSession session = request.getSession();
		session.removeAttribute("currentUser");
		session.removeAttribute("currentUserName");
		session.removeAttribute("touxiangPath");
		Cookie[] cookies = request.getCookies();
		for(Cookie c:cookies) {
			if("username".equals(c.getName())) {
				c.setMaxAge(0);
				response.addCookie(c);
			}
			if("password".contentEquals(c.getName())) {
				c.setMaxAge(0);
				response.addCookie(c);
			}
		}
		return "redirect:gauge/login.html";
	}
}
